package com.jy.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.InputStream;

/**
 * @author 羡羡
 */
public class CosFileupload {
    /**
     * SecretId 腾讯授权ID
     */
    public static String SECRET_ID="AKIDq5YrntRkDIVrc6Rc4xczOwxf6bGROrTG";
    /**
     * SECRET_KEY 腾讯授权秘钥
     */
    public static String SECRET_KEY="SeYCbgU1HK60e1C6j8I4YkbCWcVBoAPJ";
    /**
     * BUCKETNAME 储存库的名字
     */
    public static String BUCKETNAME="sls-cloudfunction-ap-guangzhou-code-1301165591";
    /**
     * REGIONID 储存库的区域编号  ap-guangzhou ：地区广州储存库
     */
    public static String REGIONID="ap-guangzhou";

    /**
     * 初始化配置信息
     * @return
     */
    public static COSClient Initialize(){
        /**
         * 初始化用户身份信息(secretId, secretKey)
         */
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        /**
         * 设置bucket的区域 http方式
         */
        ClientConfig clientConfig = new ClientConfig(new Region(REGIONID));
        /**
         * 生成cos客户端
         */
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     *文件上传
     * @param Inputstream  传文件流
     * @param key  为文件名 需要唯一
     */
    public static void upfile(InputStream Inputstream, String key){
        /**
         * 得到初始化的对象
         */
        COSClient cosin=CosFileupload.Initialize();
        ObjectMetadata metadata=new ObjectMetadata();
        PutObjectRequest request=new PutObjectRequest(BUCKETNAME,key,Inputstream,metadata);
        cosin.putObject(request);
        cosin.shutdown();
    }
    /**
     * 删除文件
     * @param key 文件名
     */
    public static void delfile(String key){
        COSClient cosdelfile=CosFileupload.Initialize();
        cosdelfile.deleteObject(BUCKETNAME,key);
        cosdelfile.shutdown();
    }
}
